/**
 * 版权所有(C)，中国银联股份有限公司，2002-2013，所有权利保留。
 * 
 * 项目名：	simple-web
 * 文件名：	RoleInfoAction.java
 * 模块说明：	
 * 修改历史：
 * 2013-11-17 - Administrator - 创建。
 */
package com.aeky.simple.action.roleInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.aeky.simple.action.BaseAction;
import com.aeky.simple.cache.CacheManager;
import com.aeky.simple.cache.CacheType;
import com.aeky.simple.cache.DataCache;
import com.aeky.simple.constants.SystemConstants;
import com.aeky.simple.entity.FunctionInfo;
import com.aeky.simple.entity.RoleFunctionInfo;
import com.aeky.simple.entity.RoleInfo;
import com.aeky.simple.enums.EnableStatusEnum;
import com.aeky.simple.service.RoleFunctionInfoService;
import com.aeky.simple.service.RoleInfoService;
import com.aeky.simple.util.DateUtil;
import com.aeky.simple.vo.ajax.ComboxVO;
import com.aeky.simple.vo.page.Pager;
import com.aeky.simple.vo.tree.TreeNode;

/**
 * 角色信息Action
 * 
 * @author wanghui
 * 
 */
public class RoleInfoAction extends BaseAction {

    private static final long serialVersionUID = 5102643593582966094L;

    @Autowired
    private RoleInfoService roleInfoService;

    @Autowired
    private RoleFunctionInfoService roleFunctionInfoService;

    /** 角色信息 */
    private RoleInfo roleInfo;

    /**
     * 初始化角色信息新增页面
     * 
     * @return
     * @throws Exception
     */
    public String initAddRoleInfo() throws Exception {
        return "initAdd";
    }

    /**
     * 初始化角色信息管理页面
     * 
     * @return
     * @throws Exception
     */
    public String initManageRoleInfo() throws Exception {
        return "initManage";
    }

    public String getRoleInfoComboxValue() throws Exception {
        List<RoleInfo> list = null;
        try {
            list = roleInfoService.queryAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<ComboxVO> comboVOList = new ArrayList<ComboxVO>();
        ComboxVO vo = null;
        if (list != null && !list.isEmpty()) {
            for (RoleInfo si : list) {
                vo = new ComboxVO(String.valueOf(si.getRoleId()), si.getRoleName());
                comboVOList.add(vo);
            }
        }
        ajaxResult = this.getJsonFromObject(comboVOList);
        return AJAX_RESULT;
    }

    /**
     * 初始化角色信息编辑
     * 
     * @return
     * @throws Exception
     */
    public String initEditRoleInfo() throws Exception {
        final Long roleId = Long.valueOf(request.getParameter("roleId"));
        final Integer version = Integer.valueOf(request.getParameter("version"));
        RoleInfo ri = null;
        try {
            ri = roleInfoService.queryRoleInfoByIDAndVersion(roleId, version);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ri == null) {
            ajaxResult = buildJSONResponse("fail", "数据版本有变，将刷新页面！");
        } else {
            ajaxResult = buildJSONResponse("success",
                            this.getJsonFromObject(converterObjectToMap(ri)));
        }
        return AJAX_RESULT;
    }

    /**
     * 子类可重写此方法添加额外的map属性
     * 
     * @param t
     * @param map
     */
    public <T> void addOtherMapValue(T t, Map<String, Object> map) {
        RoleInfo ri = (RoleInfo) t;
        map.put("roleStatusName", EnableStatusEnum.getEnumNameByValue(ri.getRoleStatus()));
        map.put("recordCrtTime", DateUtil.formatDateDefaultDisplay(ri.getRecordCrtTime()));
        map.put("recordUpdTime", DateUtil.formatDateDefaultDisplay(ri.getRecordUpdTime()));
    }

    /**
     * 编辑角色信息
     * 
     * @return
     * @throws Exception
     */
    public String editRoleInfo() throws Exception {
        final String roleId = request.getParameter("roleId");
        final String roleName = request.getParameter("roleName");
        final String roleDesc = request.getParameter("roleDesc");
        final String version = request.getParameter("version");
        final String roleFuncs = request.getParameter("roleFuncs");
        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setRoleId(Long.valueOf(roleId));
        roleInfo.setRoleName(roleName);
        roleInfo.setRoleDesc(roleDesc);
        roleInfo.setVersion(Integer.valueOf(version));
        roleInfo.setRecordUpdOperLoginName(getLoginUserName());
        try {
            roleInfoService.updateRoleInfo(roleInfo, roleFuncs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CacheManager.refreshRoleInfoCache();
        CacheManager.refreshRoleFuncInfoCache();
        ajaxResult = buildJSONResponse("success", "操作成功");
        return AJAX_RESULT;
    }

    /**
     * 新增角色信息
     * 
     * @return
     * @throws Exception
     */
    public String addRoleInfo() throws Exception {
        final String roleName = request.getParameter("roleName");
        final String roleDesc = request.getParameter("roleDesc");
        final String roleFuncs = request.getParameter("roleFuncs");
        roleInfo = new RoleInfo();
        roleInfo.setRoleName(roleName);
        roleInfo.setRoleDesc(roleDesc);
        roleInfo.setRecordCrtOperLoginName(this.getLoginUserName());
        roleInfo.setRecordUpdOperLoginName(this.getLoginUserName());
        try {
            roleInfoService.addRoleInfo(roleInfo, roleFuncs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CacheManager.refreshRoleInfoCache();
        CacheManager.refreshRoleFuncInfoCache();
        ajaxResult = buildJSONResponse("success", "角色信息添加成功！");
        return AJAX_RESULT;
    }

    /**
     * 删除角色信息
     * 
     * @return
     * @throws Exception
     */
    public String deleteRoleInfo() throws Exception {
        final String roleId = request.getParameter("roleId");
        final String version = request.getParameter("version");
        try {
            roleInfoService.deleteRoleInfo(Long.valueOf(roleId), Integer.parseInt(version));
        } catch (Exception e) {
            e.printStackTrace();
        }
        CacheManager.refreshRoleInfoCache();
        CacheManager.refreshRoleFuncInfoCache();
        ajaxResult = buildJSONResponse("success", "操作成功");
        return AJAX_RESULT;
    }

    /**
     * 分页查询角色信息
     * 
     * @return
     * @throws Exception
     */
    public String listRoleInfo() throws Exception {
        final String roleName = request.getParameter("roleName");
        final String roleDesc = request.getParameter("roleDesc");
        Pager<RoleInfo> pager = new Pager<RoleInfo>(request.getParameter("page"),
                        request.getParameter("rows"));
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("roleName", roleName);
        dataMap.put("roleDesc", roleDesc);
        try {
            pager = roleInfoService.queryRoleInfoList(pager, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ajaxResult = this.getJsonFromObject(changeToMapPager(pager));
        return AJAX_RESULT;
    }

    /**
     * 初始化角色资源信息
     * 
     * @return
     * @throws Exception
     */
    public String initRoleResource() throws Exception {
        final String roleId = request.getParameter("roleId");
        List<RoleFunctionInfo> rfiList = null;
        if (roleId != null) {
            rfiList = roleFunctionInfoService.queryRoleFunctionInfoByRoleId(Long.valueOf(roleId));
        }
        List<TreeNode> treeList = new ArrayList<TreeNode>();
        DataCache dataCache = CacheManager.getCache(CacheType.AUTH_DATA_CACHE);
        Map<String, LinkedHashMap<String, FunctionInfo>> sysFuncMap = dataCache
                        .getSysFuncInfoCache();
        for (Map.Entry<String, LinkedHashMap<String, FunctionInfo>> sysFun : sysFuncMap.entrySet()) {
            final String sysCode = sysFun.getKey();
            final LinkedHashMap<String, FunctionInfo> sysFuns = sysFun.getValue();
            TreeNode tn = new TreeNode();
            tn.setState("open");
            tn.setId(sysCode);
            tn.setText(dataCache.getSystemInfoBySysCode(sysCode).getSysName());
            tn.setChildren(initSubTreeNode_0(sysFuns, sysCode, rfiList));
            treeList.add(tn);
        }
        ajaxResult = this.getJsonFromObject(treeList);
        return AJAX_RESULT;
    }

    private List<TreeNode> initSubTreeNode_0(LinkedHashMap<String, FunctionInfo> dataList,
                    String sysCode, List<RoleFunctionInfo> rfiList) {
        List<TreeNode> resultList = new ArrayList<TreeNode>();
        for (Map.Entry<String, FunctionInfo> map : dataList.entrySet()) {
            final String funcCode = map.getKey();
            final FunctionInfo fi = map.getValue();
            if (fi.getFuncType().equals(SystemConstants.FUNCTION_INFO_TYPE_0)) {
                TreeNode tn = new TreeNode();
                tn.setId(this.getTreeId(fi.getFuncCode(), sysCode));
                tn.setText(fi.getFuncName());
                tn.setState("open");
                tn.setChildren(initSubTreeNode_1(dataList, funcCode, sysCode, rfiList));
                tn.setChecked(this.setTreeNodeChecked(funcCode, sysCode, rfiList));
                resultList.add(tn);
            }
        }
        return resultList;
    }

    private List<TreeNode> initSubTreeNode_1(LinkedHashMap<String, FunctionInfo> dataList,
                    String parent, String sysCode, List<RoleFunctionInfo> rfiList) {
        List<TreeNode> resultList = new ArrayList<TreeNode>();
        for (Map.Entry<String, FunctionInfo> map : dataList.entrySet()) {
            final String funcCode = map.getKey();
            final FunctionInfo fi = map.getValue();
            if (fi.getFuncType().equals(SystemConstants.FUNCTION_INFO_TYPE_1)
                            && fi.getParentFuncCode().equals(parent)) {
                TreeNode tn = new TreeNode();
                tn.setId(this.getTreeId(fi.getFuncCode(), sysCode));
                tn.setText(fi.getFuncName());
                tn.setState("open");
                tn.setChildren(initSubTreeNode_2(dataList, funcCode, sysCode, rfiList));
                tn.setChecked(this.setTreeNodeChecked(funcCode, sysCode, rfiList));
                resultList.add(tn);
            }
        }
        return resultList;
    }

    private List<TreeNode> initSubTreeNode_2(LinkedHashMap<String, FunctionInfo> dataList,
                    String parent, String sysCode, List<RoleFunctionInfo> rfiList) {
        List<TreeNode> resultList = new ArrayList<TreeNode>();
        for (Map.Entry<String, FunctionInfo> map : dataList.entrySet()) {
            final String funcCode = map.getKey();
            final FunctionInfo fi = map.getValue();
            if (fi.getFuncType().equals(SystemConstants.FUNCTION_INFO_TYPE_2)
                            && fi.getParentFuncCode().equals(parent)) {
                TreeNode tn = new TreeNode();
                tn.setChecked(true);
                tn.setState("open");
                tn.setId(this.getTreeId(fi.getFuncCode(), sysCode));
                tn.setText(fi.getFuncName());
                tn.setChecked(this.setTreeNodeChecked(funcCode, sysCode, rfiList));
                resultList.add(tn);
            }
        }
        return resultList;
    }

    private String getTreeId(String funcCode, String sysCode) {
        return sysCode + "-" + funcCode;
    }

    private Boolean setTreeNodeChecked(String funcCode, String sysCode,
                    List<RoleFunctionInfo> rfiList) {
        Boolean temp = Boolean.FALSE;
        if (rfiList != null && !rfiList.isEmpty()) {
            for (RoleFunctionInfo rfi : rfiList) {
                if (sysCode.equals(rfi.getSysCode()) && funcCode.equals(rfi.getFuncCode())) {
                    temp = Boolean.TRUE;
                    break;
                }
            }
        }
        return temp;
    }

    public RoleInfo getRoleInfo() {
        return roleInfo;
    }

    public void setRoleInfo(RoleInfo roleInfo) {
        this.roleInfo = roleInfo;
    }

}
